/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package vistas;

import controladores.FuncionalidadJpaController;
import controladores.UsuarioJpaController;
import entidades.Funcionalidad;
import entidades.TipoUsuario;
import entidades.Usuario;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import rn.UsuarioRN;
import rn.VehiculoRN;

/**
 *
 * @author g
 */
public class MantenimientoUsuarios extends javax.swing.JFrame {

    MyTableModel modelo_de_tabla;
    Usuario user_selected;
    private static EntityManagerFactory factory = Persistence.createEntityManagerFactory("Hormicat-SistemaIntegralPU");

    public MantenimientoUsuarios() {
        initComponents();
        List<TipoUsuario> todosTiposUsuario = UsuarioRN.getTodosTiposUsuario();
        for (TipoUsuario t : todosTiposUsuario) {
            combo_tipo_de_usuario.addItem(t);
        }
        this.setVisible(true);
        this.setLocationRelativeTo(null);
        this.setResizable(false);
    }

    private class MyTableModel extends DefaultTableModel {

        public MyTableModel(Object[][] data, Object[] columnNames) {

            super(data, columnNames);
        }

        @Override
        public Class<?> getColumnClass(int columnIndex) {
            Class<?> clazz = Object.class;
            Object aux = getValueAt(0, columnIndex);
            if (aux != null) {
                clazz = aux.getClass();
            }
            return clazz;
        }
    }

    private void iniciarModeloTabla() {
        Object datos[][] = {};
        String[] columnNames = {"Id", "Funcionalidad", "Habilitado"};
        modelo_de_tabla = new MyTableModel(datos, columnNames);
    }

    private void cargarTabla(List<Funcionalidad> resultado) {
        iniciarModeloTabla();
        for (Funcionalidad c : resultado) {
            Object fila[] = new Object[]{
                c.getId().toString(), c, false
            };
            modelo_de_tabla.addRow(fila);
        }
        tabla.setModel(modelo_de_tabla);
    }

    private void establecerPermisos() {
        try {
            List<Funcionalidad> func_habilitadas = new ArrayList();
            for (int i = 0; i < modelo_de_tabla.getRowCount(); i++) {
                boolean hab = (Boolean) tabla.getValueAt(i, 2);
                if (hab) {
                    func_habilitadas.add((Funcionalidad) tabla.getValueAt(i, 1));                
                    System.out.println((Funcionalidad) tabla.getValueAt(i, 1));
                }
            }
            user_selected.setFuncionalidads(func_habilitadas);
            new UsuarioJpaController(factory).edit(user_selected);
            JOptionPane.showMessageDialog(null, "Datos modificados");
        } catch (Exception ex) {
            Logger.getLogger(MantenimientoUsuarios.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    private void llenarCampos(Usuario u) {
        tf_apellidos.setText(u.getApellidos());
        tf_nombre.setText(u.getNombres());
        tf_usuario.setText(u.getUser_name());
        tf_pass.setText(u.getUser_password());
        combo_tipo_de_usuario.addItem(u.getTipoUsuario().get(0));        
        List<Funcionalidad> func_habilitadas = u.getFuncionalidads();
        List<Funcionalidad> todas = new FuncionalidadJpaController(factory).findFuncionalidadEntities();
        iniciarModeloTabla();
        for (Funcionalidad c : todas) {
            boolean hab = false;
            if (func_habilitadas.contains(c)) {
                hab = true;
            }
            Object fila[] = new Object[]{
                c.getId().toString(), c, hab
            };
            modelo_de_tabla.addRow(fila);
        }
        tabla.setModel(modelo_de_tabla);
    }

    private void buscarUsuario() {
        String user = tf_usuario.getText();
        String pass = tf_pass.getText();
        TipoUsuario tipo = (TipoUsuario) combo_tipo_de_usuario.getSelectedItem();

        user_selected = UsuarioRN.getUsuario(user, pass, tipo.getDescripcion());

        if (user_selected != null) {
            llenarCampos(user_selected);
        } else {
            JOptionPane.showMessageDialog(null, "Usuario o contraseña invalido");
        }
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        tf_apellidos = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        tf_nombre = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        tf_usuario = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        tf_pass = new javax.swing.JTextField();
        bt_guardar = new javax.swing.JButton();
        jLabel5 = new javax.swing.JLabel();
        combo_tipo_de_usuario = new javax.swing.JComboBox();
        bt_buscar = new javax.swing.JButton();
        jPanel2 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        tabla = new javax.swing.JTable();
        bt_modificar = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Datos personales"));

        jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        jLabel1.setText("Apellidos:");

        jLabel2.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        jLabel2.setText("Nombres:");

        jLabel3.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        jLabel3.setText("Usuario:");

        jLabel4.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        jLabel4.setText("Contraseña:");

        bt_guardar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/accept.png"))); // NOI18N
        bt_guardar.setText("Crear Usuario");
        bt_guardar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bt_guardarActionPerformed(evt);
            }
        });

        jLabel5.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        jLabel5.setText("Usuario:");

        combo_tipo_de_usuario.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        combo_tipo_de_usuario.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                combo_tipo_de_usuarioActionPerformed(evt);
            }
        });

        bt_buscar.setText("Buscar");
        bt_buscar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bt_buscarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(bt_buscar)
                        .addGap(18, 18, 18)
                        .addComponent(bt_guardar))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                .addComponent(jLabel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(jLabel2, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(jLabel3, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                            .addComponent(jLabel5, javax.swing.GroupLayout.Alignment.TRAILING))
                        .addGap(18, 18, 18)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(combo_tipo_de_usuario, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(tf_apellidos)
                            .addComponent(tf_usuario)
                            .addComponent(tf_nombre)
                            .addComponent(tf_pass))))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(17, 17, 17)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(tf_apellidos, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(tf_nombre, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(tf_usuario, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(tf_pass, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel5)
                    .addComponent(combo_tipo_de_usuario, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(14, 14, 14)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(bt_guardar)
                    .addComponent(bt_buscar))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Funcionalidades permitidas"));

        tabla.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {},
                {},
                {},
                {}
            },
            new String [] {

            }
        ));
        jScrollPane1.setViewportView(tabla);

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 353, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        bt_modificar.setText("Modificar permisos");
        bt_modificar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bt_modificarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(bt_modificar)
                .addGap(29, 29, 29))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(bt_modificar)
                .addContainerGap(15, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void bt_guardarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bt_guardarActionPerformed

        UsuarioJpaController ujc = new UsuarioJpaController(factory);
        String ape = tf_apellidos.getText();
        String nom = tf_nombre.getText();
        String user = tf_usuario.getText();
        String pass = tf_pass.getText();
        TipoUsuario tipo = (TipoUsuario) combo_tipo_de_usuario.getSelectedItem();
        Usuario u = new Usuario();
        u.setApellidos(tf_apellidos.getText());
        u.setNombres(tf_nombre.getText());
        u.setUser_name(tf_usuario.getText());
        u.setUser_password(tf_pass.getText());
        List<TipoUsuario> tipos = new ArrayList<>();
        tipos.add(tipo);
        u.setTipoUsuario(tipos);        
        ujc.create(u);
        JOptionPane.showMessageDialog(null, "Usuario creado");
        iniciarModeloTabla();
        List<Funcionalidad> resultado = new FuncionalidadJpaController(factory).findFuncionalidadEntities();
        cargarTabla(resultado);
        user_selected = UsuarioRN.getUsuario(user, pass, tipo.getDescripcion());
    }//GEN-LAST:event_bt_guardarActionPerformed

    private void combo_tipo_de_usuarioActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_combo_tipo_de_usuarioActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_combo_tipo_de_usuarioActionPerformed

    private void bt_buscarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bt_buscarActionPerformed
        buscarUsuario();
    }//GEN-LAST:event_bt_buscarActionPerformed

    private void bt_modificarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bt_modificarActionPerformed
        establecerPermisos();
        
    }//GEN-LAST:event_bt_modificarActionPerformed

  
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton bt_buscar;
    private javax.swing.JButton bt_guardar;
    private javax.swing.JButton bt_modificar;
    private javax.swing.JComboBox combo_tipo_de_usuario;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable tabla;
    private javax.swing.JTextField tf_apellidos;
    private javax.swing.JTextField tf_nombre;
    private javax.swing.JTextField tf_pass;
    private javax.swing.JTextField tf_usuario;
    // End of variables declaration//GEN-END:variables

}
